﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.SQL;
using Wicture.EPC.Service.V1.QueryInterceptors.Interceptors;
using Wicture.EPC.Service.V1.Repository;

namespace Wicture.EPC.Service.V1.QueryInterceptors
{
    public static class QueryInterceptorManager
    {
        private static List<IQueryInterceptor> interceotors;
        static QueryInterceptorManager()
        {
            interceotors = new List<IQueryInterceptor>
            {
                new BaseQueryInterceptor(),
                new HondaQueryInterceptor(),
                new BjhdQueryInterceptor(),
                new SgmQueryInterceptor(),
                new NissanQueryInterceptor(),
                new BmwQueryInterceptor(),
                new MazdaQueryInterceptor(),
                new ToyotaQueryInterceptor(),
                new JaguarQueryInterceptor(),
                new FordQueryInterceptor(),
                new GwmQueryInterceptor(),
                new ChanganQueryInterceptor(),
                new SgmwQueryInterceptor(),
                new BYDQueryInterceptor(),
                new CitroenQueryInterceptor(),
                new ChanganSuzukiQueryInterceptor(),
                new JacQueryInterceptor(),
                new KiaQueryInterceptor(),
                new LynkcoQueryInterceptor(),
                new DfskQueryInterceptor(),
                new VolvoQueryInterceptor(),
                new TrumpchiQueryInterceptor(),
                new GeelyQueryInterceptor(),
                new HaimaQueryInterceptor(),
                new SoueastQueryInterceptor(),
                new BjevQueryInterceptor(),
                new TeslaQueryInterceptor(),
                new MitsubishiQueryInterceptor(),
                new BaicQueryInterceptor(),
                new SaabQueryInterceptor(),
                new LeopQueryInterceptor(),
                new MoparQueryInterceptor(),
                new SubaruQueryInterceptor(),
                new SupercarQueryInterceptor(),
                new AlfaromeoQueryInterceptor()
            };
        }

        public static object Interceptor(DbRESTFulRepository repository, JObject param, [CallerMemberName] string targetName = "")
        {
            var brandCode = param.Value<string>("brandCode");
            var interceptor = interceotors.FirstOrDefault(i => i.BrandCodes.Contains(brandCode));
            try
            {
                return interceptor.GetType().GetMethod(targetName)?.Invoke(interceptor, new object[] { repository, param });
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.LogError(ex, $"Call {targetName} for {brandCode}.");
                throw ex.InnerException;
            }
        }
    }
}


